package ext.acae2.dms.web.input;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;

import wt.log4j.LogR;
import de.innosystec.unrar.Archive;
import de.innosystec.unrar.rarfile.FileHeader;

public class UnrarProcessor {

	private static final Logger LOGGER = LogR.getLogger(UnrarProcessor.class
			.getName());

	public String unrar(File file) throws Exception {
		LOGGER.debug("> Start unrar");
		String filePath = file.getAbsolutePath();
		LOGGER.debug("filePath: " + filePath);

		if (!filePath.toUpperCase().endsWith(".RAR")) {
			LOGGER.error("The file " + filePath + " is not rar type. return!");
			return "";
		}
		Archive rarFile = new Archive(file);

		String rootPath = makeRootFolder(filePath);
		String xmlPath = makeRarFolderAndFile(rootPath, rarFile);

		LOGGER.debug("> End unrar");
		rarFile.close();
		return xmlPath;
	}

	private String makeRootFolder(String filePath) {
		String folderPath = filePath.substring(0, filePath.lastIndexOf("."));
		LOGGER.debug("folderPath: " + folderPath);

		File rootFolder = new File(folderPath);
		rootFolder.mkdirs();

		return folderPath;
	}

	private String makeRarFolderAndFile(String rootPath, Archive rarFile)
			throws Exception {
		String xmlPath = "";
		FileOutputStream fos = null;
		try {
			FileHeader fh = rarFile.nextFileHeader();
			while (fh != null) {
				if (!fh.isDirectory()) {
					// get destDirName and destFileName
					String compressFileName = fh.getFileNameString().trim();
					LOGGER.debug("compressFileName = " + compressFileName);
					if(File.separator.equals("/")){
						compressFileName= compressFileName.replaceAll("\\\\", File.separator);
					}
					String destFileName = "";
					String destDirName = "";

					destFileName = rootPath + File.separator
							+ compressFileName;
					destDirName = destFileName.substring(0,
							destFileName.lastIndexOf(File.separator));
					LOGGER.debug("destFileName = " + destFileName);
					LOGGER.debug("destDirName = " + destDirName);

					// create folder
					File dir = new File(destDirName);
					if (!dir.exists() || !dir.isDirectory()) {
						dir.mkdirs();
					}
					// decompression file
					fos = new FileOutputStream(new File(destFileName));
					rarFile.extractFile(fh, fos);
					fos.close();
					fos = null;

					if (destFileName.toUpperCase().endsWith(".XML")) {
						xmlPath = destFileName;
					}
				}
				fh = rarFile.nextFileHeader();
			}
			rarFile.close();
			rarFile = null;
		} catch (Exception e) {
			throw e;
		} finally {
			if (fos != null) {
				try {
					fos.close();
					fos = null;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (rarFile != null) {
				try {
					rarFile.close();
					rarFile = null;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return xmlPath;
	}
}
